import React, { Component } from 'react';
import { Modal, Input, Form } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { renameComponent } from 'src/services/DataManage';

interface Iprops {
    modalVisibleValue:boolean
    modalVisible:any
    outData:any
	updateComponentInfo:any
}

const layout = {
	labelCol: { span: 10 },
	wrapperCol: { span: 14 },
};

class RenameComponent extends Component<Iprops,any> {

    formRef = React.createRef<FormInstance>();

    handleOk = () => {
    	this.formRef.current.validateFields().then(
    		value => {
    			this.handleAadOutComponent( { componentId: this.props.outData.id,...value } );
    		}
    	);
    };

    handleAadOutComponent = async data => {
    	const info = await renameComponent( { data: data } );
    	if( info.data && info.data.success ) {
    		this.props.updateComponentInfo( info.data.data );
    		this.handleCancle();
    	}
    };

    handleCancle = () => {
    	this.props.modalVisible( 'renameComponentVisible', false );
    	this.formRef.current.resetFields();
    };
    
    componentDidUpdate( prevProps: Readonly<Iprops>, prevState: Readonly<any>, snapshot?: any ): void {
    	if( this.props.modalVisibleValue!== prevProps.modalVisibleValue && this.props.outData.name ) {
    		this.formRef.current.setFieldsValue( { name: this.props.outData.name } );
    	}
    }

    render() {
    	return (
    		<Modal visible={this.props.modalVisibleValue}
    			{ ...layout } mask={false} maskClosable={false}
    			onCancel={this.handleCancle}
    			onOk={() => this.handleOk()}
    			okText="确定"
    			cancelText="取消"
    			forceRender={true}
    			title={'重命名'}>
    			<Form ref={this.formRef}>
    				<Form.Item label="名称"
    					name="name"
    					rules={[ { required: true, message: '请输入名称' } ]}>
    					<Input/>
    				</Form.Item>
    			</Form>
    		</Modal>
    	);
    }
}

export default RenameComponent;